﻿using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Manage.SysUser.Request;
using Md.Dapper.Repositories.Md;

namespace Md.Api.Service.Manage.SysUser;
/// <summary>
/// 通过用户编号获取系统用户服务
/// </summary>
public class GetSysUserByUserIdService : ApiBase<RequestGetSysUserByUserIdModel>
{
    /// <summary>
    /// 系统用户仓储
    /// </summary>
    public SysUserRep sysUserRep { get; set; }
    /// <summary>
    /// 系统角色仓储
    /// </summary>
    public SysRoleRep sysRoleRep { get; set; }
    /// <summary>
    /// 系统岗位仓储
    /// </summary>
    public SysPostRep sysPostRep { get; set; }
    /// <summary>
    /// 系统部门仓储
    /// </summary>
    public SysDeptRep sysDeptRep { get; set; }
    /// <summary>
    /// 系统用户角色关联仓储
    /// </summary>
    public SysUserRoleRep sysUserRoleRep { get; set; }
    /// <summary>
    /// 系统用户岗位关联仓储
    /// </summary>
    public SysUserPostRep sysUserPostRep { get; set; }

    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        var userData = sysUserRep.GetSysUserByUserId(Parameter.UserId);

        var deptData = new SysDeptModel();

        if (userData != null && userData.DeptId > 0)
        {
            deptData = sysDeptRep.GetSysDeptByDeptId(userData.DeptId);
        }

        var roles = sysUserRoleRep.GetSysUserRoleListByUserId(Parameter.UserId).ToList();

        var posts = sysUserPostRep.GetSysUserPostListByUserId(Parameter.UserId).ToList();

        var roleDataList = new List<SysRoleModel>();

        if (roles.Count() > 0)
        {
            foreach (var roleItem in roles)
            {
                var role = sysRoleRep.GetSysRoleByRoleId(Convert.ToInt64(roleItem.RoleId));

                if (role != null)
                {
                    roleDataList.Add(role);
                }
            }
        }

        var postDataList = new List<SysPostModel>();

        if (posts.Count() > 0)
        {
            foreach (var postItem in posts)
            {
                var post = sysPostRep.GetSysPostByPostId(Convert.ToInt64(postItem.PostId));

                if (post != null)
                {
                    postDataList.Add(post);
                }
            }
        }

        Result.Data = new { user = userData, roleIds = roles.Select(s => s.RoleId), postIds = posts.Select(s => s.PostId), dept = deptData, roleList = roleDataList, postList = postDataList };
    }
}